// http://www.baidu.com
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QNetworkReply>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 1.设置标题
    this->setWindowTitle("Http 客户端");

    // 2. 赋值变量，用来进行网络操作和处理
    manager = new QNetworkAccessManager(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    // 1. 获取到输入框的 url。
    QUrl url(ui->lineEdit->text());
    // 2. 构造一个 HTTP 请求对象
    QNetworkRequest request(url);
    // 3. 发送请求
    QNetworkReply* response = manager->get(request);
    // 4. 通过信号槽，来处理响应
    connect(response, &QNetworkReply::finished, [=](){
       if(response->error() == QNetworkReply::NoError) {
           // 响应正确获取到了
           QString html = response->readAll();
           ui->plainTextEdit->setPlainText(html);
       } else {
           // 响应出错了
           ui->plainTextEdit->setPlainText(response->errorString());
       }
       // 还需要对 response 进行释放
       response->deleteLater();
    });
}
